#!/usr/bin/python3
# -*- coding: utf8 -*-
"""
说明: 环境变量`YUAN_JING`账号密码`-`分割，多账户用&隔开[例如：aaa-bbb&ccc-ddd]
环境变量`YJ_COOKIE`多账户用&隔开或换行隔开
[YJ_COOKIE为cookie值，只需要包含jqCP_887f_saltkey=xxxx；jqCP_887f_auth=xxxx；字段即可]
cron: 20 9 */7 * *
new Env('远景论坛-签到');
"""

import hashlib, re
import requests
import os, time, random

try:
    from sendNotify import send
except:
    def send(*args):
        print("未找到通知文件sendNotify.py不启用通知！")

# from bs4 import BeautifulSoup

List = []

# 内置Python环境变量[纯Python环境可启用]
#os.environ['YUAN_JING'] = ""
#os.environ['YJ_COOKIE'] = ""

user_agent = 'Mozilla/5.0 (Linux; Android 10; PBEM00) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.52 Mobile Safari/537.36'


def login_task(usr, pwd):
    session = requests.Session()
    login_data = 'https://bbs.pcbeta.com/member.php?mod=logging&action=login&mobile=yes'
    headers = {'referer': 'https://bbs.pcbeta.com', 'user-agent': user_agent}
    rehash = session.get(login_data, headers=headers)
    pattern_loginhash = ";loginhash=(.+?)[&\|;\|\"]"
    pattern_formhash = "formhash.*value=[\|'\|\"](.+?)['\|\"]"
    loginhash = re.findall(pattern_loginhash, str(rehash.text))
    formhash0 = re.findall(pattern_formhash, str(rehash.text))
    login_url = f"https://bbs.pcbeta.com/member.php?mod=logging&action=login&loginsubmit=yes&loginhash={','.join(loginhash)}&inajax=1"
    headers = {
        'origin': 'https://bbs.pcbeta.com',
        'referer': 'https://bbs.pcbeta.com/member.php?mod=logging&action=login&mobile=yes',
        'user-agent': user_agent
    }
    data = {
        'formhash': f"{','.join(formhash0)}",
        'referer': 'https://bbs.pcbeta.com/',
        'username': usr,
        'password': hashlib.md5(pwd.encode('utf-8')).hexdigest(),
        'questionid': 0,
        'cookietime': '2592000'
    }
    res = session.post(login_url, headers=headers, data=data)
    if res.status_code == 200:
        if "欢迎您回来" in res.text:
            pattern_formhash = "formhash=(.+?)[<\|&\|\"\|']"
            formhash = re.findall(pattern_formhash, str(res.text))
            pattern_name = "username\">(.+?)[<\|&]"
            username = re.findall(pattern_name, str(res.text))
            List.append(f"[账户`{','.join(username)}`]登陆成功")
            List.append(f"formhash值：{','.join(formhash)}")
            get_task_url = 'https://i.pcbeta.com/home.php?mod=task&mobile=no'
            task_head = {
                'referer': 'https: //i.pcbeta.com/home.php?mod=task',
                'user-agent': user_agent
            }
            resk = session.get(get_task_url, headers=task_head)
            if "每日打卡" in resk.text:
                get_check_url = 'https://i.pcbeta.com/home.php?mod=task&do=apply&id=149'
                check_head = {'referer': get_task_url, 'user-agent': user_agent}
                resg = session.get(get_check_url, headers=check_head)
                List.append("签到成功！") if "恭喜您，任务已成功完成" in resg.text else List.append(f"{resg.text}")
            elif "新任务" in resk.text:
                List.append("已经签过到了")
            else:
                List.append(f"未知错误，错误信息如下\n{resk.text}")
        elif "登录失败" in res.text:
            List.append(f"账号登陆失败: 账号或密码错误")
            pattern = "[<p>\|[](登录失败.+?)[</p>\|<]"
            List.append(f"{re.findall(pattern, res.text, re.S)[0]}")
        elif "多次输入密码错误" in res.text:
            List.append(f"多次输入密码错误，请 30 分钟之后再次尝试登录！")
        else:
            List.append(f"登录出错，错误信息如下\n{res.text}")
    else:
        List.append(f"登录出错，错误信息如下\n{res.text}")


def cookie_task():
    #session = requests.Session()
    get_task_url = 'https://i.pcbeta.com/home.php?mod=task&mobile=no'
    get_tasking_url = 'https://i.pcbeta.com/home.php?mod=task&item=doing&mobile=no'
    task_head = {
        'referer': 'https: //i.pcbeta.com/home.php?mod=task',
        'user-agent': user_agent,
        'cookie': cookie
    }
    resk = requests.get(get_task_url, headers=task_head)
    tasking_head = {'referer': get_task_url, 'user-agent': user_agent, 'cookie': cookie}
    resd = requests.get(get_tasking_url, headers=tasking_head)
    if "每日打卡" in resk.text or "每日打卡任务" in resd.text:
        get_check_url = 'https://i.pcbeta.com/home.php?mod=task&do=apply&id=149'
        check_head = {'referer': get_task_url, 'user-agent': user_agent, 'cookie': cookie}
        resg = requests.get(get_check_url, headers=check_head)
        if "恭喜您，任务已成功完成" in resg.text:
            List.append("签到成功！")
        else:
            check_draw_head = {'referer': get_tasking_url, 'user-agent': user_agent, 'cookie': cookie}
            draw_check_url = 'https://i.pcbeta.com/home.php?mod=task&do=draw&id=149'
            resa = requests.get(draw_check_url, headers=check_draw_head)
            List.append("签到奖励领取成功！") if "恭喜您，任务已成功完成" in resa.text else List.append(f"{resa.text}")        
    elif "需要先登录" in resk.text:
        List.append("您的cookie已过期请重新获取！")
        return 1
    elif "新任务" in resk.text and "每日打卡" not in resd.text:
        List.append("已经签过到了")
    else:
        List.append(f"未知错误，错误信息如下\n{resk.text}")


if __name__ == '__main__':
    delay_sec = random.randint(1,122)
    List.append(f'随机延时{delay_sec}s')
    time.sleep(delay_sec)
    global users
    i = 0
    if 'YJ_COOKIE' in os.environ:
        cookies = os.environ['YJ_COOKIE'].split('\\n') if '\\n' in os.environ['YJ_COOKIE'] else os.environ['YJ_COOKIE'].split('\n') if '\n' in os.environ['YJ_COOKIE'] else os.environ['YJ_COOKIE'].split('&')
        List.append(f'当前使用的是cookie签到')
        if 'YUAN_JING' in os.environ:
            users = os.environ['YUAN_JING'].split('&')
            if len(cookies) == len(users):
                num = True
            else:
                num = False
                List.append(f'cookie数量和用户名密码数量不相同，若cookie失效后不使用账户密码签到！！！')
        else:
            num = False
            List.append(f'没有填写YUAN_JING变量，不启用账户密码登陆')
        for cookie in cookies:
            i += 1
            List.append(f'===> [账号{str(i)}]Start <===')
            t = cookie_task()
            if t == 1 and num == True:
                List.append(f'改用账户密码签到')
                for x in users[i - 1:]:
                    name, pwd = x.split('-')
                    login_task(name, pwd)
            List.append(f'===> [账号{str(i)}]End <===\n')
            time.sleep(1)
        tt = '\n'.join(List)
        print(tt)
        send('远景论坛', tt)
    elif 'YUAN_JING' in os.environ:
        users = os.environ['YUAN_JING'].split('&')
        List.append(f'当前使用的是账户密码签到')
        for x in users:
            i += 1
            name, pwd = x.split('-')
            List.append(f'===> [账号{str(i)}]Start <===')
            login_task(name, pwd)
            List.append(f'===> [账号{str(i)}]End <===\n')
            time.sleep(1)
        tt = '\n'.join(List)
        print(tt)
        send('远景论坛', tt)
    else:
        print('未配置环境变量')
        send('远景论坛', '未配置环境变量')
